﻿using System;
using System.Collections.Generic;
using System.Linq;

using DM4;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.Data.WcfLinq;
using DevExpress.XtraTab;
using DevExpress.XtraBars;
using System.Data.Services.Client;
using System.Data;
using sscore.Utils;
using sscore;

namespace DM4Client
{
    public partial class FrmMain
    {
        private void initLog(bool first)
        {
            XMLInfo xi = GetUserList();
            DataTable usersTable = XMLInfo.FillTable(xi);
            var _users = ComboUtils.DataTableToDict(usersTable, "usr_id", "usr_name", DM4Consts.SDefaultNULLId, "All");
            Common.FillComboWithSetId(beiLogUser, ricbLogUser.Items, _users, Currentuserid.ToString(), false);

            xi = Dm4Srv.GetModulesList();
            DataTable modulesTable = XMLInfo.FillTable(xi);
            var _modules = ComboUtils.DataTableToDict(modulesTable, "mod_code", "mod_code", DM4Consts.SDefaultNULLId, "All");
            Common.FillComboWithSetId(beiLogModule, ricbLogModule.Items, _modules, DM4Consts.SDefaultNULLId, false);

            xi = GetSessionsList();
            DataTable sessionsTable = XMLInfo.FillTable(xi);
            var _sessions = ComboUtils.DataTableToDict(sessionsTable, "sess_id", "sess_id", DM4Consts.SDefaultNULLId, "All");
            Common.FillComboWithSetId(beiLogSession, ricbLogSession.Items, _sessions, DM4Consts.SDefaultNULLId, false);

            OperationResult op = GetDaemonsList();
            if (op.Result == DM4Consts.Ok)
            {
                var _daemons = StringUtils.StringToParams(op.Message);
                Dictionary<string, ParamEntry> _daemonsForCombo = new Dictionary<string, ParamEntry>();
                _daemonsForCombo.Add("-1", new ParamEntry("All"));
                foreach (var daemons in _daemons) _daemonsForCombo.Add(daemons.Key, daemons.Value);
                Common.FillComboWithSetId(beiLogDaemons, ricbLogDaemons.Items, _daemonsForCombo, DM4Consts.SDefaultNULLId, false);
            }
            
            if (first)
            {
                beiLogFrom.EditValue = DateTime.Now;
                beiLogTo.EditValue = DateTime.Now;
                beiLogMessType.EditValue = DM4Consts.SDefaultNULLId;
            }
        }

        private void rbiRefreshLog_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            RefreshLog(_fLog.tcLogs.SelectedTabPage);
        }

        private void LogPageChanged(object sender, TabPageChangedEventArgs e)
        {
            RefreshLog(((XtraTabControl)sender).SelectedTabPage, true);
        }

        private void RefreshLog(XtraTabPage page, bool skipData = false)
        {
            //закоменчено для быстоты, чтобы не грузило
            //initLog(false)

            string pageName = page.Name;

            GridControl grid = _fLog.logGrid.dgLog;
            GridView view = _fLog.logGrid.gvLog;

            BeginWait();
            try
            {
                try
                {
                    try
                    {
                        switch (pageName)
                        {
                            case "tpLogTest":
                            case "tpLogError":
                            case "tpLogGeneral":
                                beiLogUser.Visibility = BarItemVisibility.Always;
                                beiLogModule.Visibility = BarItemVisibility.Always;
                                beiLogSession.Visibility = BarItemVisibility.Always;
                                beiLogDaemons.Visibility = BarItemVisibility.Never;
                                break;
                            case "tpLogSystem":
                                beiLogUser.Visibility = BarItemVisibility.Never;
                                beiLogModule.Visibility = BarItemVisibility.Never;
                                beiLogSession.Visibility = BarItemVisibility.Never;
                                beiLogDaemons.Visibility = BarItemVisibility.Never;
                                break;
                            case "tpLogDaemons":
                                beiLogUser.Visibility = BarItemVisibility.Never;
                                beiLogModule.Visibility = BarItemVisibility.Never;
                                beiLogSession.Visibility = BarItemVisibility.Never;
                                beiLogDaemons.Visibility = BarItemVisibility.Always;
                                break;
                        }

                        Common.ItemInfo usrIdSelect = (Common.ItemInfo)beiLogUser.EditValue;
                        Common.ItemInfo modCodeSelect = (Common.ItemInfo)beiLogModule.EditValue;
                        Common.ItemInfo sessIdSelect = (Common.ItemInfo)beiLogSession.EditValue;
                        Common.ItemInfo daemonSelect = (Common.ItemInfo)beiLogDaemons.EditValue;
                        string messTypeSelect = beiLogMessType.EditValue == null ? "" : (string)beiLogMessType.EditValue;
                        string startDateSelect = String.Format("{0}-{1}-{2}", ((DateTime)beiLogFrom.EditValue).Year, ((DateTime)beiLogFrom.EditValue).Month.ToString("D2"), ((DateTime)beiLogFrom.EditValue).Day.ToString("D2"));
                        string stopDateSelect = String.Format("{0}-{1}-{2}", ((DateTime)beiLogTo.EditValue).Year, ((DateTime)beiLogTo.EditValue).Month.ToString("D2"), ((DateTime)beiLogTo.EditValue).Day.ToString("D2"));
                        DateTime startDate = new DateTime(((DateTime)beiLogFrom.EditValue).Year, ((DateTime)beiLogFrom.EditValue).Month, ((DateTime)beiLogFrom.EditValue).Day);
                        DateTime stopDate = (new DateTime(((DateTime)beiLogTo.EditValue).Year, ((DateTime)beiLogTo.EditValue).Month, ((DateTime)beiLogTo.EditValue).Day)).AddDays(1);

                        foreach (XtraTabPage pageControl in _fLog.tcLogs.TabPages)
                            pageControl.Controls.Remove(_fLog.logGrid);

                        page.Controls.Add(_fLog.logGrid);

                        if (skipData)
                        {
                            grid.DataSource = null;
                        }
                        else
                        {
                            if (LogDataClasses != null)
                            {
                                switch (pageName)
                                {
                                    case "tpLogDaemons":
                                        var selectedOrdersDaemons = from log in LogDataClasses.log_daemons where log.lg_time >= startDate && log.lg_time <= stopDate select log;
                                        if (beiLogUser.Visibility == BarItemVisibility.Always && usrIdSelect != null && usrIdSelect.Id != "-1") selectedOrdersDaemons = from log in selectedOrdersDaemons where log.lg_usr_id == Convert.ToInt32(usrIdSelect.Id) select log;
                                        if (beiLogDaemons.Visibility == BarItemVisibility.Always && daemonSelect != null && daemonSelect.Id != "-1") selectedOrdersDaemons = from log in selectedOrdersDaemons where log.lg_mod_code == daemonSelect.Id select log;
                                        if (messTypeSelect != null && messTypeSelect != "-1") selectedOrdersDaemons = from log in selectedOrdersDaemons where log.lg_mess_type == Convert.ToInt32(messTypeSelect) select log;
                                        _fLog.linqServerModeSourceLog.QueryableSource = selectedOrdersDaemons;
                                        break;
                                    case "tpLogError":
                                        var selectedOrdersError = from log in LogDataClasses.log_error_views where log.lg_time >= startDate && log.lg_time <= stopDate select log;
                                        if (beiLogUser.Visibility == BarItemVisibility.Always && usrIdSelect != null && usrIdSelect.Id != "-1") selectedOrdersError = from log in selectedOrdersError where log.lg_usr_id == Convert.ToInt32(usrIdSelect.Id) select log;
                                        if (beiLogModule.Visibility == BarItemVisibility.Always && modCodeSelect != null && modCodeSelect.Id != "-1") selectedOrdersError = from log in selectedOrdersError where log.lg_mod_code == modCodeSelect.Id select log;
                                        if (beiLogSession.Visibility == BarItemVisibility.Always && sessIdSelect != null && sessIdSelect.Id != "-1") selectedOrdersError = from log in selectedOrdersError where log.lg_sess_id == sessIdSelect.Id select log;
                                        if (messTypeSelect != null && messTypeSelect != "-1") selectedOrdersError = from log in selectedOrdersError where log.lg_mess_type == Convert.ToInt32(messTypeSelect) select log;
                                        _fLog.linqServerModeSourceLog.QueryableSource = selectedOrdersError;
                                        break;
                                    case "tpLogGeneral":
                                        var selectedOrdersGeneral = from log in LogDataClasses.log_general_views where log.lg_time >= startDate && log.lg_time <= stopDate select log;
                                        if (beiLogUser.Visibility == BarItemVisibility.Always && usrIdSelect != null && usrIdSelect.Id != "-1") selectedOrdersGeneral = from log in selectedOrdersGeneral where log.lg_usr_id == Convert.ToInt32(usrIdSelect.Id) select log;
                                        if (beiLogModule.Visibility == BarItemVisibility.Always && modCodeSelect != null && modCodeSelect.Id != "-1") selectedOrdersGeneral = from log in selectedOrdersGeneral where log.lg_mod_code == modCodeSelect.Id select log;
                                        if (beiLogSession.Visibility == BarItemVisibility.Always && sessIdSelect != null && sessIdSelect.Id != "-1") selectedOrdersGeneral = from log in selectedOrdersGeneral where log.lg_sess_id == sessIdSelect.Id select log;
                                        if (messTypeSelect != null && messTypeSelect != "-1") selectedOrdersGeneral = from log in selectedOrdersGeneral where log.lg_mess_type == Convert.ToInt32(messTypeSelect) select log;
                                        _fLog.linqServerModeSourceLog.QueryableSource = selectedOrdersGeneral;
                                        break;
                                    case "tpLogSystem":
                                        var selectedOrdersSystem = from log in LogDataClasses.log_systems where log.lg_time >= startDate && log.lg_time <= stopDate select log;
                                        if (beiLogUser.Visibility == BarItemVisibility.Always && usrIdSelect != null && usrIdSelect.Id != "-1") selectedOrdersSystem = from log in selectedOrdersSystem where log.lg_usr_id == Convert.ToInt32(usrIdSelect.Id) select log;
                                        if (beiLogModule.Visibility == BarItemVisibility.Always && modCodeSelect != null && modCodeSelect.Id != "-1") selectedOrdersSystem = from log in selectedOrdersSystem where log.lg_mod_code == modCodeSelect.Id select log;
                                        if (messTypeSelect != null && messTypeSelect != "-1") selectedOrdersSystem = from log in selectedOrdersSystem where log.lg_mess_type == Convert.ToInt32(messTypeSelect) select log;
                                        _fLog.linqServerModeSourceLog.QueryableSource = selectedOrdersSystem;
                                        break;
                                    case "tpLogTest":
                                        var selectedOrdersTest = from log in LogDataClasses.log_test_views where log.lg_time >= startDate && log.lg_time <= stopDate select log;
                                        if (beiLogUser.Visibility == BarItemVisibility.Always && usrIdSelect != null && usrIdSelect.Id != "-1") selectedOrdersTest = from log in selectedOrdersTest where log.lg_usr_id == Convert.ToInt32(usrIdSelect.Id) select log;
                                        if (beiLogModule.Visibility == BarItemVisibility.Always && modCodeSelect != null && modCodeSelect.Id != "-1") selectedOrdersTest = from log in selectedOrdersTest where log.lg_mod_code == modCodeSelect.Id select log;
                                        if (beiLogSession.Visibility == BarItemVisibility.Always && sessIdSelect != null && sessIdSelect.Id != "-1") selectedOrdersTest = from log in selectedOrdersTest where log.lg_sess_id == sessIdSelect.Id select log;
                                        if (messTypeSelect != null && messTypeSelect != "-1") selectedOrdersTest = from log in selectedOrdersTest where log.lg_mess_type == Convert.ToInt32(messTypeSelect) select log;
                                        _fLog.linqServerModeSourceLog.QueryableSource = selectedOrdersTest;
                                        break;
                                }

                                _fLog.linqServerModeSourceLog.DefaultSorting = "lg_id DESC";
                                _fLog.linqServerModeSourceLog.KeyExpression = "lg_id";

                                //grid.ServerMode = true;
                                grid.DataSource = null;
                                grid.DataSource = _fLog.linqServerModeSourceLog;
                            }
                            else
                            {
                                //create filter
                                List<string> where = new List<string>();

                                where.Add(String.Format("lg_time ge datetime'{0}'", startDateSelect));
                                where.Add(String.Format("lg_time le datetime'{0}T23:59:59'", stopDateSelect));
                                if (beiLogUser.Visibility == BarItemVisibility.Always && usrIdSelect != null && usrIdSelect.Id != "-1") where.Add(String.Format("lg_usr_id eq {0}", usrIdSelect.Id));
                                if (beiLogModule.Visibility == BarItemVisibility.Always && modCodeSelect != null && modCodeSelect.Id != "-1") where.Add(String.Format("lg_mod_code eq '{0}'", modCodeSelect.Id));
                                if (beiLogSession.Visibility == BarItemVisibility.Always && sessIdSelect != null && sessIdSelect.Id != "-1") where.Add(String.Format("lg_sess_id eq '{0}'", sessIdSelect.Id));
                                if (beiLogDaemons.Visibility == BarItemVisibility.Always && daemonSelect != null && daemonSelect.Id != "-1") where.Add(String.Format("lg_mod_code eq '{0}'", daemonSelect.Id));
                                if (messTypeSelect != null && messTypeSelect != "-1") where.Add(String.Format("lg_mess_type eq {0}", messTypeSelect));

                                WcfServerModeSource wsms = new WcfServerModeSource() { DefaultSorting = "lg_id DESC", KeyExpression = CnLog.Id };

                                DataServiceQuery selectedLog = null;
                                switch (pageName)
                                {
                                    case "tpLogDaemons":
                                        selectedLog = LogEntities.log_daemons.AddQueryOption("$filter", String.Join(" and ", where.ToArray()));
                                        break;
                                    case "tpLogError":
                                        selectedLog = LogEntities.log_error_view.AddQueryOption("$filter", String.Join(" and ", where.ToArray()));
                                        break;
                                    case "tpLogGeneral":
                                        selectedLog = LogEntities.log_general_view.AddQueryOption("$filter", String.Join(" and ", where.ToArray()));
                                        break;
                                    case "tpLogSystem":
                                        selectedLog = LogEntities.log_system.AddQueryOption("$filter", String.Join(" and ", where.ToArray()));
                                        break;
                                    case "tpLogTest":
                                        selectedLog = LogEntities.log_test_view.AddQueryOption("$filter", String.Join(" and ", where.ToArray()));
                                        break;
                                }
                                wsms.Query = selectedLog;

                                grid.DataSource = null;
                                grid.DataSource = wsms;
                            }
                        }

                        _fLog.logGrid.gcLgMessType.VisibleIndex = 0;
                        _fLog.logGrid.gcLgTime.VisibleIndex = 1;
                        _fLog.logGrid.gcLgModCode.VisibleIndex = 2;
                        _fLog.logGrid.gcLgSession.VisibleIndex = 3;
                        _fLog.logGrid.gcLgMessage.VisibleIndex = 4;
                        _fLog.logGrid.gcLgUsrId.VisibleIndex = 5;

                        _fLog.logGrid.gcLgModCode.Visible = true;
                        _fLog.logGrid.gcLgUsrId.Visible = true;

                        switch (pageName)
                        {
                            case "tpLogDaemons":
                                _fLog.logGrid.gcLgUsrId.Visible = false;
                                _fLog.logGrid.gcLgModCode.Caption = "Daemon";
                                _fLog.logGrid.gcLgSession.Visible = false;
                                break;
                            case "tpLogSystem":
                                _fLog.logGrid.gcLgModCode.Visible = false;
                                _fLog.logGrid.gcLgUsrId.Visible = false;
                                _fLog.logGrid.gcLgModCode.Caption = "Module";
                                _fLog.logGrid.gcLgSession.Visible = false;
                                break;
                            default:
                                _fLog.logGrid.gcLgModCode.Caption = "Module";
                                _fLog.logGrid.gcLgSession.Visible = true;
                                break;
                        }

                        view.BeginUpdate();
                        try
                        {
                            if (view.RowCount > 0)
                                view.MoveFirst();
                        }
                        finally
                        {
                            view.EndUpdate();
                        }
                        grid.Focus();
                        view.BestFitColumns();
                    }
                    catch (Exception ex)
                    {
                        //SERVER IS DOWN!! NEED RECONNECT                   
                        WriteError(ex.Message);
                        LoginToService();
                    }
                }
                catch (Exception ex)
                {
                    WriteError(ex.Message);
                }
            }
            finally
            {
                EndWait();
            }
        }
    }
}
